package com.itheima.interceptor;

import com.itheima.context.BaseContext;
import com.itheima.properties.JwtProperties;
import com.itheima.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
    用户拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ////TODO:: 请补充代码 判断是否有token，如果有校验通过后放行，否则返回 错误信息： NOT_LOGIN
        log.info("进入拦截器");
        //判断当前拦截到的是Controller的方法还是其他资源
        if(!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        try {
            //在请求头中获取令牌
            String token = request.getHeader(jwtProperties.getTokenName());
            //校验令牌
            log.info("jwt校验：{}",token);
            //获取用户自定义数据
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            //设置用户的id
            Long userId = Long.valueOf(claims.get("id").toString());
            log.info("登录的用户id为{}",userId);
            BaseContext.setCurrentId(userId);
            //通过，放行
            return true;
        } catch (Exception e) {
           //不通过
            log.error("jwt令牌解析失败{}",e.getMessage());
            response.setStatus(401);
            return false;
        }
    }
}
